package com.mojo.netty;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 基于socket的服务-线程池处理
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/26 11:14
 */
public class SocketServer03 {
//    328     (RPS: 9.5)                      Status 303:    328
//
//    RPS: 10.5 (requests/second)
//    Max: 4102ms
//    Min: 2000ms
//    Avg: 3534.6ms
//
//  50%   below 4004ms
//  60%   below 4004ms
//  70%   below 4005ms
//  80%   below 4007ms
//  90%   below 4013ms
//  95%   below 4036ms
//  98%   below 4051ms
//  99%   below 4058ms
//99.9%   below 4102ms
//350     (RPS: 10.2)
    public static void main(String[] args) throws IOException {
        int nThreads = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
        System.out.println(nThreads);
        final ServerSocket serverSocket = new ServerSocket(8888);
        while (true) {
            try {
                final Socket accept = serverSocket.accept();
                //线程池处理accept
                executorService.execute(() -> service(accept));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void service(Socket accept) {
        try (OutputStream out = accept.getOutputStream();
             PrintWriter writer = new PrintWriter(out, true);) {
            Thread.sleep(20);
            writer.println("HTTP1.1 200 OK");
            writer.println("ContentType:text/html;charset=utf-8");
            writer.println();
            writer.println("hello socket server");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
